/*
 * MIT License
 *
 * Copyright (c) 2023-present, tangli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package tony.mybatis.datascope.interceptor

import java.sql.Connection
import net.sf.jsqlparser.expression.Expression
import net.sf.jsqlparser.schema.Table
import org.apache.ibatis.executor.Executor
import org.apache.ibatis.executor.statement.StatementHandler
import org.apache.ibatis.mapping.BoundSql
import org.apache.ibatis.mapping.MappedStatement
import org.apache.ibatis.session.ResultHandler
import org.apache.ibatis.session.RowBounds
import org.springframework.core.PriorityOrdered
import tony.mybatis.datascope.IDataScopeContext
import tony.mybatis.datascope.handler.ScopedDataPermissionHandler
import tony.mybatis.datascope.model.current

/**
 * [IDataScopeContext]驱动的 数据权限拦截器
 * @author tangli
 * @date 2025/09/15 16:36
 */
internal open class ScopedDataPermissionInterceptor(
    private val scopedDataPermissionHandler: ScopedDataPermissionHandler,
) : DataPermissionInterceptor(),
    PriorityOrdered {
    override fun beforeQuery(
        executor: Executor?,
        ms: MappedStatement,
        parameter: Any?,
        rowBounds: RowBounds?,
        resultHandler: ResultHandler<*>?,
        boundSql: BoundSql?,
    ) {
        if (!current.isBound) {
            return
        }
        super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql)
    }

    override fun beforePrepare(
        sh: StatementHandler,
        connection: Connection?,
        transactionTimeout: Int?,
    ) {
        if (!current.isBound) {
            return
        }
        super.beforePrepare(sh, connection, transactionTimeout)
    }

    override fun buildTableExpression(
        table: Table,
        where: Expression,
        whereSegment: String,
    ): Expression? =
        if (!current.isBound) {
            null
        } else {
            scopedDataPermissionHandler.getSqlSegment(
                table,
                where,
                whereSegment,
                current.get()
            )
        }

    override fun getOrder(): Int =
        PriorityOrdered.HIGHEST_PRECEDENCE
}
